//
//  WmcHomeVC.swift
//  YPWatermarkCamera
//
//  Created by 赵新 on 2022/3/1.
//

import Foundation
import Photos
import UIKit
import YPBedrock
import YPGraphicEngine
import YPNetwork
import SnapKit

// MARK: - 扩展WmcHomeVC + WmcNavigatorProtocol

extension WmcHomeVC: WmcNavigatorProtocol {
    static func navigationPaths() -> [WmcNavigatorManager.Path] {
        return [.home]
    }

    static func willMakeNavigationVC(with parms: WmcNavigatorManager.Parms) -> UIViewController {
        let vc = WmcHomeVC()
        return vc
    }
}

// MARK: - 扩展WmcHomeVC + WmcVMProtocol

extension WmcHomeVC: WmcVMProtocol {
    typealias VMType = WmcHomeVM
}

// MARK: - [WmcHomeVC]


open class WmcHomeVC: WmcBaseVC {



    // Internal

    lazy var headerView: WmcHomeHeaderView = {
        let view = WmcHomeHeaderView()
        return view
    }()
    
    lazy var noticeView: WmcHomeNoticeView = {
        let view = WmcHomeNoticeView()
        return view
    }()

    lazy var cameraBackgroundView: UIView = {
        let view = UIView()
        view.backgroundColor = .black
        return view
    }()

    var cameraView: YPGECameraView?

    lazy var controlView: WmcHomeControlView = {
        let view = WmcHomeControlView()
        return view
    }()

    /// 重新定位
    lazy var positioningBtn: WmcTopImgBottomTextBtn = {
        let btn = WmcTopImgBottomTextBtn.CreateHomeHeaderBtn(title: "重新定位", image: "home_tool_location".wmc_image)
        btn.contentEdge = UIEdgeInsets(top: 8, left: 2, bottom: 4, right: 2)
        btn.label.font = UIFont.systemFont(ofSize: 11)
        btn.layer.shadowColor = UIColor.wmc_grayH5_606066.cgColor
        btn.layer.shadowRadius = 4
        btn.layer.shadowOffset = CGSize(width: 0, height: 1)
        btn.layer.shadowOpacity = 0.8
        btn.layer.cornerRadius = 8
        return btn
    }()
    /// 水印容器视图
    lazy var watermarkContentView: WmcWatermarkContentView = {
        let view = WmcWatermarkContentView()
        return view
    }()

    lazy var videoRecordingLabel: UILabel = {
        let label = UILabel.YP.Create(font: 22.yp.uiFont(weight: .bold),
                                      color: UIColor.white,
                                      alignment: .center)
        label.backgroundColor = .wmc_red_F54A45
        label.layer.cornerRadius = 4
        label.layer.masksToBounds = true
        label.isHidden = true
        return label
    }()

    lazy var videoRecording50STipsLabel: UILabel = {
        let label = UILabel.YP.Create(text: "超过60S的视频需手动上传至相册",
                                      font: 16,
                                      color: UIColor.white,
                                      alignment: .center)
        label.backgroundColor = .black.yp.alpha(0.8)
        label.layer.cornerRadius = 4
        label.layer.masksToBounds = true
        label.isHidden = true
        return label
    }()

    lazy var footerView: WmcHomeFooterView = {
        let view = WmcHomeFooterView()
        return view
    }()
    
    lazy var customFooterView: UIView? = {
        let view = homeDelegate?.toolCustomView(.current)
        return view
    }()

    /// 水印选择控件
    lazy var watermarkSelectView: WmcSelectWatermarkPreviewView = {
        let view = WmcSelectWatermarkPreviewView()
        return view
    }()

    /// 模式选择
    lazy var functionSelectView: WmcFunctionSelectView = {
        let functionSelectView = WmcFunctionSelectView()
        return functionSelectView
    }()

    /// 定位状态视图
//    lazy var locationTipView: WmcLocateIssueTipView = {
//        let view = WmcLocateIssueTipView(type: .unauthorized)
//        view.isHidden = true
//        return view
//    }()

    /// 网络错误弹窗
    lazy var networkErrorTipView: WmcLocateIssueTipView = {
        let view = WmcLocateIssueTipView(type: .failure)
        view.isHidden = true
        return view
    }()

    /// 本相机不能修改时间视图
    lazy var modifyTimeTipView: WmcModifyTimeTipView = {
        let view = WmcModifyTimeTipView()
        view.isHidden = true
        return view
    }()

    lazy var setCommonAddressView: WmcCommonAddressTipView = {
        let view = WmcCommonAddressTipView()
        view.isHidden = true
        return view
    }()

    /// 点击设置常用地点定位更精确气泡
    lazy var locationGuideView: WmcLocateGuideTipView = {
        let view = WmcLocateGuideTipView()
        view.isHidden = true
        return view
    }()

    /// 用于锁全屏操作的
    lazy var lockActionView: WmcHomeLockActionView = {
        let view = WmcHomeLockActionView()
        view.isHidden = true
        return view
    }()

    /// 画幅比例view
    private(set) lazy var aspectRatioView: WmcHomeAspectRatioView = {
        let view = WmcHomeAspectRatioView()
        // 默认隐藏
        view.isHidden = true
        return view
    }()
    /// 闪光灯模式选择view
    private(set) lazy var flashSelectView: WmcHomeFlashSelectView = {
        let view = WmcHomeFlashSelectView()
        // 默认隐藏
        view.isHidden = true
        return view
    }()

    /// 滤镜view
    private(set) lazy var filterView: WmcHomeImageFilterView = {
        let view = WmcHomeImageFilterView()
        view.items = viewModel.filterItems
        // 默认隐藏
        view.isHidden = true
        return view
    }()
    
    /// 静态二维码视图(用作展示)
    private(set) lazy var staticQRView: WmcQRCodeVerifyView = {
        let view = WmcQRCodeVerifyView()
        return view
    }()
    
    
    /// 动态二维码视图(用于生成照片)
    private(set) lazy var dynamicQRView: WmcQRCodeVerifyView = {
        let view = WmcQRCodeVerifyView()
        return view
    }()
    
    /// 二维码验证用户引导
    private(set) lazy var qrVerifyGuideView: WmcQRCodeVerifyGuideView = {
        let view = WmcQRCodeVerifyGuideView()
        // 默认隐藏
        view.isHidden = true
        return view
    }()
    /// 排版按钮
    private(set) lazy var layoutButton: WmcTopImgBottomTextBtn = {
        let btn = WmcTopImgBottomTextBtn(title: "排版", image: "icon_photo_layout_32".wmc_image)
        btn.textColor = UIColor.wmc_white_FFFFFF
        btn.font = 13.wmc_scaleFont(weight: .medium)
        return btn
    }()
    /// 照片布局父视图
    private lazy var photoLayoutContainerView: UIView = {
        let view = UIView()
        view.isUserInteractionEnabled = false
        return view
    }()
    /// 照片布局view
    private(set) lazy var photoLayoutView: WmcHomePhotoLayoutView = {
        let view = WmcHomePhotoLayoutView()
        let setting = self.viewModel.combinePhotoSetting
        view.style = setting.style
        view.columns = setting.columns.rawValue
        view.totalCount = setting.columns.photoNum
        view.reload()
        return view
    }()
    /// 拼图引导view
    private(set) lazy var combineGuideView: WmcCombinePhotoGuideView = {
        let view = WmcCombinePhotoGuideView()
        view.isHidden = true
        return view
    }()
    
    private(set) lazy var focusAdjustView: WmcHomeControlFocusAdjustView = {
        let view = WmcHomeControlFocusAdjustView()
        view.set(scale: 1.0, isShowScales: false)
        return view
    }()
    /// 相机权限(未授权)提示
    private(set) lazy var cameraPermissonTipView: WmcHomeCameraPermissionTipView = {
        let view = WmcHomeCameraPermissionTipView()
        return view
    }()

    /// 是否开启重力感应反馈
    var isAccelerometerFeedback: Bool = true

    /// 气泡表
    var bubbleViewMap: [String: WmcBubbleView] = [:]


    /// 首页的外部代理
    var homeDelegate: WmcHomeDelegate? {
        return YPWmcManager.shared.uiDelegate.homeDelegate
    }
    

    let hMargin = 16.0.wmc_autoHor
    let qrcodeW = 60.wmc_autoHor
    let qrcodeH = 80.wmc_autoHor
    /// 是否显示过顶部定位提示
    var hasLocationTipShown: Bool = false
    
    
    // MARK: Lifecycle
    override open func viewDidLoad() {
        super.viewDidLoad()

        WmcDateManager.shared.requestDate()
        // 请求高德隐私
        WmcLocationManager.requestPrivecy()

        // 弹窗调度
        viewModel.alertScheduler()

        // 加载业务总线
//        viewModel.loadBusinessBus()
        // 获取上一次使用的水印
        viewModel.getLastUseWatermark()
        
        // 获取上一次的拍照识别
        viewModel.queryLastSelectedRecognitionType { [weak self] model in
            guard let weakSelf = self else { return }
            weakSelf.controlView.aiLogoView.updateModel(model)
        }

        // 检查网络环境
        let networkType = YPNetworkReachability.queryNetworkReachabilityType()
        checkNetworkStatus(type: networkType)

    }
    
    override open func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        // 开启相机(保险起见)
        startCamera()
        // 重置焦距
        resetCameraFocusScale()
        // 重感反馈
        isAccelerometerFeedback = true
        WmcMotionManager.shared.start()
        // 方位角
        WmcCLLocationManager.shared.startUpdatingHeading()
        // 噪音
        let microphoneStatus = WmcAuthorizedManager.microphone()
        if microphoneStatus.info.isAvailable { // 有权限直接开启
            WmcDecibeManager.shared.start()
        }
        // 加载相关数据
        viewModel.loadData()
        footerView.updateCloudAlbumBtnStatus()
        updateCloudAlbumRedPoint()

        // 是否需要认证水印
        let showCertification = !WmcPreferenceSettingsManager.shared.cameraSetting.hiddenOfficialMark

        watermarkContentView.reloadWatermark(showCertification: showCertification)
        
        updateSyncStatus()
    }
    
    override open func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        // 重置曝光
        cameraView?.setExposure(0)
        // 设置闪光灯按钮隐藏与否
        headerView.refreshFlashBtnState(cameraView)
        // 设置常用地址弹窗
        if let poi = WmcTaskSchedulerManager.shared.commonAddress {
            WmcTaskSchedulerManager.shared.commonAddress = nil
            setCommonAddressView.updateModel(poi: poi)
        }
        // 恢复手电筒
        restoreElectricTorch()
    }


    override open func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        // 重感反馈
        isAccelerometerFeedback = false
        WmcMotionManager.shared.stop()
        // 顶部菜单隐藏
//        headerMenuShow(false)
        // 画幅比例隐藏
        setAspectRatioView(shown: false)
        // 隐藏滤镜view
        setFilterView(shown: false)
        // 隐藏新手引导
        locationGuideView.isHidden = true
    }
  

    override open func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        // 关闭相机
        stopCamera()
        if modifyTimeTipView.isHidden == false {
            modifyTimeTipView.dismiss()
        }
        turnOffElectricTorch(cacheState: false)
    }

    open override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        if !viewModel.hasShowQRGuide && qrVerifyGuideView.maskFrame == .zero && staticQRView.frame != .zero {
            let maskFrame = view.convert(staticQRView.frame, to: qrVerifyGuideView)
            qrVerifyGuideView.maskFrame = maskFrame
        }
    }

    // MARK: Bind VM
    override func bindDriving() {
        // 外部代理
        // 移除最后一次使用水印的缓存
        YPWmcDrivingManager.shared.home_clearWatermarkLastCacheBlock = {
            WmcUserdefault.remove(forKey: .Data.lastUseWatermark())
        }
        // 添加通知视图
        YPWmcDrivingManager.shared.home_addNoticeViewBlock = { [weak self] (view, key) in
            guard let weakSelf = self else { return }
            weakSelf.noticeView.addNoticeView(view, key: key)
        }
        // 移除通知视图
        YPWmcDrivingManager.shared.home_removeNoticeViewBlock = { [weak self] key in
            guard let weakSelf = self else { return }
            weakSelf.noticeView.removeNoticeView(key)
        }
        // 设置水印模型
        YPWmcDrivingManager.shared.home_replaceWatermarkBlock = { [weak self] watermarkModel in
            guard let weakSelf = self else { return }
            weakSelf.viewModel.setWatermarkModel(watermarkModel)
        }
        // 保存图片到本地相册
        YPWmcDrivingManager.shared.home_savePhotoToLocalAlbumBlock = { [weak self] result in
            guard let weakSelf = self else { return }
            weakSelf.viewModel.saveImage(watermarkPhoto: result.0,
                                         standardPhoto: result.1,
                                         watermarkModel: result.2,
                                         qrcodePhoto: result.3)
        }
        // 上传视频到云相册
        YPWmcDrivingManager.shared.home_uploadVideoToLocalAlbumBlock = { [weak self] result in
            guard let weakSelf = self else { return }
            weakSelf.viewModel.uploadVideo(videoPath: result.videoPath,
                                           previewImagePath: result.videoCoverPath,
                                           videoTime: result.videoTime,
                                           watermarkModel: result.watermarkModel,
                                           breakOffType: .none)
        }
        // 向相机控制试图添加提示视图
        YPWmcDrivingManager.shared.home_addCameraControlTipsBlock = { [weak self] key, view in
            guard let weakSelf = self else { return }
            weakSelf.controlView.addTipsView(key: key, view: view)
        }
        // 移除相机控制试图的提示视图
        YPWmcDrivingManager.shared.home_removeCameraControlTipsBlock = { [weak self] key in
            guard let weakSelf = self else { return }
            weakSelf.controlView.removeTipsView(key: key)
        }
        // 移除所有相机控制试图的提示视图
        YPWmcDrivingManager.shared.home_removeAllCameraControlTipsBlock = { [weak self] in
            guard let weakSelf = self else { return }
            weakSelf.controlView.removeAllTipsViews()
        }
        // 拍照事务
        YPWmcDrivingManager.shared.home_takePhotoActionBlock = { [ weak self] in
            guard let weakSelf = self else { return }
            weakSelf.clickTakePhoto()
        }
        // 水印列表
        YPWmcDrivingManager.shared.home_showWatermarkListActionBlock = { [ weak self] in
            guard let weakSelf = self else { return }
            weakSelf.showWatermarkAlertView()
        }
        // 数钢筋水印列表
        YPWmcDrivingManager.shared.home_showObjectRecognitionAlertView = { [weak self] in
            guard let weakSelf = self else { return }
            weakSelf.showObjectRecognitionAlertView()
        }
        // 切换前后置摄像头
        YPWmcDrivingManager.shared.home_shotCutActionBlock = { [ weak self] in
            guard let weakSelf = self else { return }
            weakSelf.clickFlip()
        }
        // 前后切换
        YPWmcDrivingManager.shared.home_setCameraPosition = { [ weak self] position in
            guard let weakSelf = self else { return }
            if weakSelf.cameraView?.position() != position {
                weakSelf.clickFlip()
            }
        }
        
        // 功能模式切换
        YPWmcDrivingManager.shared.home_switchFunctionMode = { [weak self] functionMode in
            guard let weakSelf = self else { return }
            weakSelf.switchFunctionMode(functionMode)
        }
    }

    override func bindViewAction() {
        viewActionBind()
    }

    override func bindViewModel() {
        viewModelBind()
    }

    // MARK: UI
    override func makeUI() {
        
        let hMargin = 16.0.wmc_autoHor
        // 添加相机视图
        addSubview(cameraBackgroundView)
        // 相机水印视图
        addSubview(watermarkContentView)
        // 通知视图
        addSubview(noticeView)
        // 相机控制视图
        addSubview(controlView)
        // 导航视图
        addSubview(headerView)
        headerView.frame = CGRect(x: 0, y: 0, width: Wmc_screenWidth, height: Wmc_statusBarHeight + 44)
        headerView.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(Wmc_statusBarHeight + 44)
        }
        // 模式选择视图(拍照/视频/数钢筋...)
        addSubview(functionSelectView)
        // 底部拍摄工具栏
        addSubview(footerView)
        
        if let customFooterView = customFooterView {
            let contentFooterView = WmcHomeCustomContentView()
            contentFooterView.hitBlock = { [weak self] in
                guard let weakSelf = self else { return }
                weakSelf.setAspectRatioView(shown: false)
            }
            addSubview(contentFooterView)
            contentFooterView.snp.makeConstraints { make in
                make.top.left.right.bottom.equalTo(footerView)
            }
            footerView.isHidden = true
            functionSelectView.isHidden = true
            
            contentFooterView.addSubview(customFooterView)
            customFooterView.snp.makeConstraints { make in
                make.edges.equalToSuperview()
            }
        }
        
        // 画幅比例
        addSubview(aspectRatioView)
        aspectRatioView.snp.makeConstraints { make in
            make.top.equalTo(headerView.snp.bottom).offset(8)
            make.left.equalTo(Wmc_standardEdge.left)
            make.right.equalTo(-Wmc_standardEdge.right)
            make.height.equalTo(70)
        }
        // 闪光灯模式选择
        addSubview(flashSelectView)
        flashSelectView.snp.makeConstraints { make in
            make.edges.equalTo(aspectRatioView)
        }
        
        // 视频录制计时器
        addSubview(videoRecordingLabel)
        videoRecordingLabel.snp.makeConstraints { make in
            make.bottom.equalTo(footerView.snp.top).offset(-4)
            make.centerX.equalToSuperview()
            make.size.equalTo(CGSize(width: 85, height: 35))
        }

        // 录制50秒提示
        addSubview(videoRecording50STipsLabel)
        videoRecording50STipsLabel.snp.makeConstraints { make in
            make.bottom.equalTo(videoRecordingLabel.snp.top).offset(-12)
            make.centerX.equalToSuperview()
            make.height.equalTo(50)
            make.width.equalTo(260)
        }

        // 重新定位按钮
        addSubview(positioningBtn)
        positioningBtn.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(-12)
            make.bottom.equalTo(footerView.snp.top).offset(-12)
            make.size.equalTo(CGSize(width: 56, height: 56))
        }

        // 设置常用地址弹窗
        addSubview(setCommonAddressView)
        setCommonAddressView.snp.makeConstraints { make in
            make.top.equalTo(headerView.snp.bottom).offset(16)
            make.left.equalTo(16)
            make.right.equalTo(-16)
            make.height.equalTo(76)
        }

        // 顶部定位状态view
//        addSubview(locationTipView)
//        locationTipView.snp.makeConstraints { make in
//            make.top.equalTo(headerView.snp.bottom).offset(16)
//            make.left.equalTo(16)
//            make.right.equalTo(-16)
//            make.height.equalTo(136)
//        }

        addSubview(networkErrorTipView)
        networkErrorTipView.snp.makeConstraints { make in
            make.top.equalTo(headerView.snp.bottom).offset(16)
            make.left.equalTo(16)
            make.right.equalTo(-16)
            make.height.equalTo(96)
        }

        // 顶部禁止修改时间view
        addSubview(modifyTimeTipView)
        modifyTimeTipView.snp.makeConstraints { make in
            make.top.equalTo(headerView.snp.bottom).offset(16)
            make.left.equalTo(16)
            make.right.equalTo(-16)
            make.height.equalTo(62)
        }

        // 点击设置常用地址气泡
        addSubview(locationGuideView)
        locationGuideView.snp.makeConstraints { make in
            make.width.equalTo(128)
            make.height.equalTo(58)
            make.right.equalTo(positioningBtn.snp.right).offset(-10)
            make.bottom.equalTo(positioningBtn.snp.top)
        }

        // 滤镜选择View
        addSubview(filterView)
        filterView.snp.makeConstraints { make in
            make.top.equalTo(footerView)
            make.left.right.bottom.equalToSuperview()
        }
        
        // 相机权限(未授权)提示
        addSubview(cameraPermissonTipView)
        cameraPermissonTipView.snp.makeConstraints { make in
            make.centerY.equalTo(cameraBackgroundView)
            make.left.equalTo(hMargin)
            make.right.equalTo(-hMargin)
        }
        let cameraStatus = WmcAuthorizedManager.camera()
        cameraPermissonTipView.isHidden = cameraStatus.info.isAvailable
        
        
        // 动态二维码视图
        // 设置控件位置(位于屏幕外面)
        dynamicQRView.frame.origin = CGPoint(x: -10000.0, y: -10000.0)
        addSubview(dynamicQRView)
        // 静态二维码图标
        view.insertSubview(staticQRView, belowSubview: positioningBtn)
        staticQRView.snp.makeConstraints { make in
            make.top.equalTo(headerView.snp.bottom).offset(hMargin)
            make.right.equalTo(-hMargin)
            make.width.equalTo(qrcodeW)
            make.height.equalTo(qrcodeH)
        }
        
        // 二维码引导
        addSubview(qrVerifyGuideView)
        qrVerifyGuideView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        // 照片布局view
        view.insertSubview(photoLayoutContainerView, belowSubview: headerView)
        photoLayoutContainerView.snp.makeConstraints { make in
            make.top.equalTo(headerView.snp.bottom)
            make.bottom.equalTo(footerView.snp.top)
            make.left.right.equalToSuperview()
        }
        photoLayoutContainerView.addSubview(photoLayoutView)
        photoLayoutView.snp.makeConstraints { make in
            make.center.equalToSuperview()
        }
        
        // 排版按钮
        addSubview(layoutButton)
        layoutButton.snp.makeConstraints { make in
            make.right.equalTo(-hMargin)
            make.width.equalTo(35.0.wmc_autoHor)
            make.height.equalTo(60.0.wmc_autoHor)
            make.bottom.equalTo(footerView.snp.top).offset(-120.0.wmc_autoHor)
        }
        
        // 拼图引导
        addSubview(combineGuideView)
        combineGuideView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        // 焦距倍数选择
        view.insertSubview(focusAdjustView, belowSubview: staticQRView)
        let focusAdjustVH = focusAdjustView.fittedHeight()
        focusAdjustView.snp.makeConstraints { make in
            make.top.equalTo(headerView.snp.bottom).offset(120.0.wmc_autoVer)
            make.right.equalTo(-12.0.wmc_autoHor)
            make.height.equalTo(focusAdjustVH)
        }
  
        

        // 设置初始画幅
        setInitialAspectRatio()

        // 设置初始清晰度
        setInitialArticulation()
        
        // 设置初始分辨率
        setInitialResolution()

        // 设置初始闪光灯

        // 设置重力感应
        deviceMotionGravitySensor()

        // 设置锁全部操作的视图
        addSubview(lockActionView)
        lockActionView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }

        // 设置延时拍照时不需要锁操作的视图
        lockActionView.ignores = [
            // 除水印相机平台以外的其他平台都忽略返回按钮事件
//            .init(view: headerView.backControl, platforms: [.watermarkCamera], isreverseSelect: true) // 产品说不需要
        ]
    }
    
    /// 二维码的显示隐藏
    func updateQRCodeViewHidden() {
        if case .photo = viewModel.functionMode {
            staticQRView.isHidden = !viewModel.showQrcodeVerify
        } else {
            staticQRView.isHidden = true
        }
        dynamicQRView.isHidden = staticQRView.isHidden
    }
    /// 二维码用户引导显示隐藏
    func updateQRGuideViewHidden() {
        if case .photo = viewModel.functionMode {
            if !viewModel.hasShowQRGuide {
                view.insertSubview(staticQRView, belowSubview: qrVerifyGuideView)
            }
            qrVerifyGuideView.isHidden = viewModel.hasShowQRGuide
        } else {
            qrVerifyGuideView.isHidden = true
        }
    }

    /// 设置初始清晰度
    func setInitialArticulation() {
        if let cacheArticulation: Int = WmcUserdefault.object(forKey: .State.Camera.videoArticulation),
           let articulation: YPGEVideoBuffer.Articulation = .init(rawValue: cacheArticulation)
        {
            WmcDebug("读取视频清晰度====>\(cacheArticulation)")
            viewModel.articulation = articulation
        } else {
            WmcDebug("默认视频清晰度")
            viewModel.articulation = ._720p
        }
        cameraView?.setWriterArticulation(viewModel.articulation)
    }

    /// 设置初始画幅
    func setInitialAspectRatio() {
        if let function = functionSelectView.firstSelectFunction() {
            switch function {
            case .edit: break
                
            case .rebarCount: // 数钢筋画幅比永远16:9
                setAspectRatio(.ar_4_3, animated: false)
                
            case .photo: // 设置相机画幅比为4：3默认，缓存
                if let cacheAspectRatio: Int = WmcUserdefault.object(forKey: .State.Camera.aspectRatio),
                   let aspectRatio: YPGESunglasses.AspectRatio = .init(rawValue: cacheAspectRatio)
                {
                    viewModel.photoAspectRatio = aspectRatio
//                    headerMenuView.aspectRatioBtn.aspectRatio = aspectRatio
                    headerView.aspectRatioBtn.aspectRatio = aspectRatio
                    setAspectRatio(aspectRatio, animated: false)
                    aspectRatioView.aspectRatio = aspectRatio
                } else {
                    setAspectRatio(animated: false)
                    viewModel.photoAspectRatio = .ar_4_3
                }
            case .video: // 视频画幅比永远16:9
                setAspectRatio(.ar_16_9, animated: false)
            case .photoAndCombine: // 画幅比例4:3固定
                setAspectRatio(.ar_4_3, animated: false)
            case .custom:
                break
            }
        }
    }
    
    /// 设置初始分辨率
    func setInitialResolution() {
        if let value: Int = WmcUserdefault.object(forKey: .State.Camera.resolution) {
            viewModel.resolutionLevel = WmcResolution.Level(rawValue: value) ?? .standard
        } else {
            viewModel.resolutionLevel = .standard
        }
        // 更新相机的分辨率
        setCameraPreset()
    }
    /// 初始化闪光灯状态
//    func setInitialFlashMode() {
//        if let cacheFlashMode: Int = WmcUserdefault.object(forKey: .State.Camera.flashMode),
//           let flashMode: YPGECamera.FlashMode = .init(rawValue: cacheFlashMode)
//        {
//            setFlashMode(flashMode, cacheState: false)
//        }
//    }

    override func backAction() {
        // 取消延迟
        cancelDelayTakePhoto()
        // 送积分业务线挽留
        if viewModel.business_integralRelay.value?.tip == 1 { // 有资格
            retainAlertBack() // 走业务线
        } else { // 直接退出
            YPWmcManager.dismiss()
        }
    }
}
